package com.kayo.specimen.resolver;

import com.alibaba.fastjson.JSON;
import com.kayo.specimen.annotion.JsonParam;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.naming.NameNotFoundException;

@Component
public class JsonArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        JsonParam parameterAnnotation = parameter.getParameterAnnotation(JsonParam.class);
        String parameterAnnotationName = parameterAnnotation.name();
        String name = parameterAnnotationName.isEmpty() ? parameter.getParameterName() : parameterAnnotation.name();
        String value = webRequest.getParameter(name);
        if (value == null || value.isEmpty())
            throw new NameNotFoundException(name + "字段参数没有找到");

        return JSON.parseObject(value, parameter.getParameterType());
    }
}
